<?php
/**
 * Created by PhpStorm.
 * Author: Shadow
 * Date: 2022/6/7
 * Time: 1:35 下午
 * description: OrderBusiness.php
 * 订单业务逻辑类
 */

namespace app\home\business;

use app\common\model\CouponLogs;
use app\common\model\SpecGoods;
use app\common\model\Address;
use app\common\model\Coupon;
use app\common\model\CouponReceive;
use app\common\model\OrderGoods;
use think\exception\DbException;
use think\facade\Db;

class OrderBusiness {

    /**
     *  用户地址信息
     *  商品清单信息
     *  获取订单详情
     */
    public static function getOrderInfo(){
        $userId = UserBusiness::getUserId();

        $address = Address::where('user_id',$userId)->select()->toArray();
        # 清单信息 购物车表里面is_selected字段值为1的、就是用户想要购买的商品

        $goods = \app\common\model\Cart::with(['spu','sku'])
            ->where('user_id','=',$userId)
            ->where('is_selected',1)
            ->visible([
                'spu' => ['goods_name','goods_logo'],
                'sku' => ['price','value_names','store_count']
            ])
            ->select()->toArray();
        # 计算总数、总价格
        $total_number = array_sum(array_column($goods,'number',NULL));
        $total_price= 0;
        foreach ($goods as $key => $item) {
            $total_price += $item['number'] * $item['sku']['price'];
            # 判断是否有库存
            if ($item['sku']['store_count'] >=$item['number'] ) {
                $goods[$key]['is_store'] = 1;
            } else {
                $goods[$key]['is_store'] = 0;
            }
            unset($goods[$key]['sku']['store_count']);
        }

        $coupon = CouponReceive::field('pyg_coupon_receive.*,c.with_amount,c.used_amount,c.title,c.icon')->join('coupon c','c.id=pyg_coupon_receive.coupon_id')->where('buyer_id',$userId)->select()->toArray();

        return [
            'address' => $address ?: [],
            'goods' => $goods ?: [],
            'total_price' => $total_price,
            'total_number' => $total_number,
            'coupon' => $coupon
        ];
    }

    /**
     * 我的订单
     */
    public static function myOrder(){

    }

    /**
     * @param $user_id
     * @param $addressInfo * 地址信息
     * @param $couponInfo * 优惠卷信息
     * @throws \think\exception\PDOException
     */
    public static function createOrder($user_id,$addressInfo,$couponInfo){

        # 查询的是购物车的选中的商品
        $goods = \app\common\model\Cart::with(['spu','sku'])
            ->where('user_id','=',$user_id)
            ->where('is_selected',1)
            ->visible([
                'spu' => ['goods_name','goods_logo'],
                'sku' => ['price','value_names','store_count','store_frozen']
            ])
            ->select()->toArray();
        # 计算总数、总价格

        $total_price= 0;

        foreach ($goods as $key => $item) {
            $total_price += $item['number'] * $item['sku']['price'];
            # 判断是否有库存
            if ($item['sku']['store_count'] < $item['number'] ) {
                abort(2003,$item['spu']['goods_name']."<font color='red'>库存不足</font>");
            }

        }

        # 创建订单之前 进行判断 使用优惠卷、并且订单总金额、不满足优惠卷使用的条件
        if (count($couponInfo) > 0 && $couponInfo['with_amount'] > $total_price) {
            abort(2004,"订单总金额不满足优惠卷的使用条件");
        }
        $coupon_price = isset($couponInfo['used_amount'])  ? $couponInfo['used_amount'] :0;//优惠的金额

        // 启动事务
        Db::startTrans();
        try {


            // 应付金额  =  商品总价  + 运费
            // 实付金额 = 应付金额 - 优惠抵扣
            # 添加订单基本信息 1000 0000  => 4 /100/9888 // 长度一样、值不一样
            $order_sn = time().str_pad($user_id,8,0,STR_PAD_LEFT);
            $create_at = time();
            $order = [
                'order_sn' => $order_sn,//订单编号
                'user_id' => $user_id,//用户id
                'order_status' =>0,//订单状态
                'consignee' => $addressInfo['consignee'],// 收货人
                'address' => $addressInfo['area'],//收获地址
                'phone' => $addressInfo['phone'],//电话
                'user_note' =>'备注',//备注
                'goods_price' => $total_price,//备注
                'shipping_price' => 0,//配送费
                'coupon_price' =>$coupon_price,//抵扣金额
                'order_amount' => $total_price,//应付金额
                'total_amount' => bcsub($total_price,$coupon_price),//实付金额
                'create_time' => $create_at,//创建时间
            ];

            $result = \app\common\model\Order::create($order);
            if (!$result) {
                abort(2004,'订单信息添加失败');
            }
            $order_id = $result->id;
            $orderGoods = [];
            $storeGoods = [];
            # 添加订单详情信息（商品）批量添加
            foreach ($goods as $item) {
                $orderGoods[] =[
                    'order_id' => $order_id,//订单id
                    'goods_id' => $item['goods_id'],//spuid
                    'spec_goods_id' => $item['spec_goods_id'], //skuid
                    'number' => $item['number'], //购买数量
                    'goods_name' => $item['spu']['goods_name'], //商品名称
                    'goods_logo' => $item['spu']['goods_logo'], //商品名称
                    'goods_price' => $item['sku']['price'], //商品单价
                    'spec_value_names' => $item['sku']['value_names'], //商品单价
                    'status' => 0,
                    'create_time' => time(),
                ];
                $storeGoods[]= [
                    'id' => $item['spec_goods_id'],
                    'store_count' => $item['sku']['store_count'] - $item['number'],//库存减去购买数量
                    'store_frozen' => $item['sku']['store_frozen'] + $item['number'],//冻结库存加上购买数量
                ];
            }

            $res = (new OrderGoods()) -> saveAll($orderGoods);

            if (!$res) {
                abort(2004,"订单详细信息添加失败");
            }

            # 维护库存
            (new SpecGoods())->saveAll($storeGoods);
            # 删除购物车的数据
            \app\common\model\Cart::where('user_id',$user_id)->where('is_selected','1')->delete();
//            使用优惠卷需要添加优惠卷使用表添加数据
            if (count($couponInfo) > 0) {
                CouponLogs::create([
                    'buyer_id' => $user_id,
                    'coupon_receive_id' => $couponInfo['id'],//领取的id
                    'order_id' => $order_id,//领取的id
                    'order_original_amount' => $total_price,//原始金额
                    'coupon_amount' => $coupon_price,//优惠金额
                    'status' => 0,//是否使用成功 0 未成功 1成功
                    'order_final_amount' => $result->total_amount,// 最终的金额
                ]);
            }

            // 提交事务
            Db::commit();

            return [
                'order_sn' => $order_sn,
                'order_amount' => $total_price,
                'total_amount' => $result->total_amount,
                'coupon_price' => $coupon_price,
                'create_at' => $create_at
            ];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            abort(2001,"下单失败");
        }
    }
    /**
     *
     * 请求支付 参数
     * 私钥进行加密
     * 支付宝 根据我们给他们公钥
     *
     * 支付宝请求品优购
     * 支付宝的私钥加密
     *
     * 拿支付宝公钥进行解密
     */
}